﻿using System.Collections.Generic;
using System.Data.SqlClient;
using FBProject.BusinessLogic.MSProjectProxies;

namespace FBProject.BusinessLogic.FBImport
{
    public class FBDBImport : FBImportBase
    {

        public override IDictionary<string, ExternalTask> ReadExternalTasks()
        {
            var listOfExternalTasks = new Dictionary<string, ExternalTask>();

            var msProjectProxy = new MSProjectProxy(MSProjectApplicationProxy.GetMSProjectApplication());
            using (var connection = new SqlConnection(msProjectProxy.FBDBConnectionString))
            // using (var connection = new SqlConnection(@"Data Source=aus-dev-sql-03.swdev.local;Initial Catalog=fogbugz;Persist Security Info=True;User ID=readonly;Password=readonly;"))
            {
                connection.Open();

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = string.Format(msProjectProxy.FBSqlQueryTemplate, msProjectProxy.FBSqlQueryAdditionalJoins, msProjectProxy.FBSqlQueryWhere);
                    command.CommandType = System.Data.CommandType.Text;

                    using (var reader = command.ExecuteReader())
                    {
                        var columnNames = new string[reader.FieldCount];
                        for (var fieldIndex = 0; fieldIndex < reader.FieldCount; fieldIndex++)
                        {
                            columnNames[fieldIndex] = reader.GetName(fieldIndex);
                        }

                        var columnIndexes = this.GetColumnIndexes(columnNames);

                        while (reader.Read())
                        {
                            var values = new object[reader.FieldCount];
                            reader.GetValues(values);
                            var externalTask = GetExternalTask(columnIndexes, values);
                            listOfExternalTasks.Add(externalTask.TaskNumber, externalTask);
                        }
                    }
                }
            }

            return listOfExternalTasks;
        }

    }
}
